package 前缀和;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @PackageName: 前缀和
 * @ClassName: LeetCode1170
 * @Author: chen jinxu
 * @Date: 2023/6/11 11:08
 * @Description: // 比较字符串最小字母出现频次
 * 定义一个函数f(s)，统计s中（按字典序比较）最小字母的出现频次 ，其中 s是一个非空字符串。
 * <p>
 * 例如，若s = "dcce"，那么f(s) = 2，因为字典序最小字母是"c"，它出现了2 次。
 * <p>
 * 现在，给你两个字符串数组待查表queries和词汇表words 。对于每次查询queries[i] ，需统计 words 中满足f(queries[i])< f(W)的
 * 词的数目 ，W 表示词汇表words中的每个词。
 * 请你返回一个整数数组answer作为答案，其中每个answer[i]是第 i 次查询的结果。
 * 输入：queries = ["cbd"], words = ["zaaaz"]
 * 输出：[1]
 * 解释：查询 f("cbd") = 1，而 f("zaaaz") = 3 所以 f("cbd") < f("zaaaz")。
 * 输入：queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
 * 输出：[1,2]
 * 解释：第一个查询 f("bbb") < f("aaaa")，第二个查询 f("aaa") 和 f("aaaa") 都 > f("cc")。e）
 * 链接：https://leetcode.cn/problems/compare-strings-by-frequency-of-the-smallest-character
 * 1 <= queries.length <= 2000
 * 1 <= words.length <= 2000
 * 1 <= queries[i].length, words[i].length <= 10
 * queries[i][j]、words[i][j] 都由小写英文字母组成
 */
public class LeetCode1170 {
    public static void main(String[] args) {
        List<Integer> collect = Arrays.stream(numSmallerByFrequency(new String[]{"cbd"}, new String[]{"zaaaz"})).boxed().collect(Collectors.toList());
        System.out.println(collect);
        List<Integer> collect1 = Arrays.stream(numSmallerByFrequency(new String[]{"bbb","cc"}, new String[]{"a", "aa", "aaa", "aaaa"})).boxed().collect(Collectors.toList());
        System.out.println(collect1);
    }

    public static int[] numSmallerByFrequency(String[] queries, String[] words) {
        int[] count = new int[12];
        for (String word : words) {
            count[f(word)]++;
        }
        for (int i = 9; i >= 1; i--) {
            count[i] += count[i + 1];
        }
        int[] res = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            String s = queries[i];
            res[i] = count[f(s) + 1];
        }
        return res;
    }

    public static int f(String s) {
        int cnt = 0;
        char ch = 'z';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c < ch) {
                cnt = 1;
                ch = c;
            } else if (ch == c) {
                cnt++;
            }
        }
        return cnt;
    }
}
